package com.example.demo.service.impl;

import com.example.demo.entity.Dakamingxi;
import com.example.demo.service.BaseService;
import com.example.demo.service.DaKaService;
import com.example.demo.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;



@Service
public class DaKaServiceImpl implements DaKaService,BaseService {
    public static List<Dakamingxi> dakamingxiList1=new ArrayList<>();
    @Autowired
    RestTemplate restTemplate;

    public List getLogList() {
        HttpHeaders requestHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(type);
        requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        //获取token
        String token = getToken(USERNAME, PASSWORD, requestHeaders);
        //获取站点
        requestHeaders.add("X-AUTH-TOKEN", token);
        List<String> sites = getSites(requestHeaders);

        if (StringUtils.isEmpty(sites)) {
            return Collections.emptyList();
        }
        //查询站点下用户登录日志
        List list = new ArrayList();
        for (String site : sites) {
            List<Dakamingxi> logList = getLogList(site, requestHeaders);
            list.addAll(logList);
        }
        return list;
    }

    private String getToken(String username, String password, HttpHeaders requestHeaders) {

        Map map = new HashMap();
        map.put("userName", username);
        map.put("password", password);
        HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
        ResponseEntity<String> response = restTemplate.postForEntity(TOKEN_URL, requestEntity, String.class);
        JSONObject jsonResponse = new JSONObject(response.getBody());
        JSONObject jsonObject=jsonResponse.getJSONObject("data");
        return jsonObject.get("token_id").toString();
    }

    private List<String> getSites(HttpHeaders requestHeaders) {
        HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
        ResponseEntity<String> response = restTemplate.exchange(SITE_URL,HttpMethod.GET, requestEntity, String.class);
        JSONObject jsonResponse = new JSONObject(response.getBody());
        JSONArray jsonObject=jsonResponse.getJSONArray("data");
        List list = new ArrayList();
        for (int i = 0; i < jsonObject.length(); i++) {
            String id = jsonObject.getJSONObject(i).getString("id");
            list.add(id);
        }
        return list;
    }

    private List<Dakamingxi> getLogList(String site, HttpHeaders requestHeaders) {
        HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
        List<Dakamingxi> dakamingxiList3=new ArrayList<>();
        //站点下所有的登录信息
        Boolean flag = true;
        String nextRowkey = "";
        String startRowkey = "";
        String url = null;
        List<JSONObject> jsonObjectList = new ArrayList<>();
        while (flag) {
            url = LOGURL + "pageSize=200&siteId=" + site
                    + "&beginTime=1587139200&endTime=1587195300&sceneName=1&startQueryRowKey=" + startRowkey;
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET,requestEntity, String.class);
            JSONObject jsonResponse = new JSONObject(response);
            JSONObject jsonResponses = new JSONObject(response.getBody());
            JSONObject jsonArrays = (JSONObject) jsonResponses.get("data");
            JSONArray jsonArray1 = jsonArrays.getJSONArray("deviceLog");
            jsonArray1.forEach(jsonobejct->{
                Dakamingxi sBuffer = new Dakamingxi();
                Dakamingxi dakamingxi= null;
                try {
                    dakamingxi = arrayIdToString((JSONObject) jsonobejct,sBuffer,site);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                dakamingxiList1.add(dakamingxi);
            });

            //按条件过滤
            dakamingxiList1 = dakamingxiList1.stream().filter(dakamingxi ->
                    !dakamingxi.getUname().contains("[WLAN_STA_INFO_AP_ASSOCIATE]"))
                    .collect(Collectors.toList());
            System.out.println(dakamingxiList1.size());
            Map<String, List<Dakamingxi>> collect = dakamingxiList1.stream().collect(Collectors.groupingBy(Dakamingxi::getMac));
            //内部遍历 比较，获取最早的打卡时间
            collect.entrySet().forEach(entry ->
            {
                dakamingxiList1 = entry.getValue();
                Optional<Dakamingxi> dakamingxi = dakamingxiList1.stream()
                        .sorted(Comparator.comparing(Dakamingxi::getFirsttime))
                        .collect(Collectors.toList()).stream().findFirst();
                dakamingxiList3.add(dakamingxi.get()); //放入集合中
            });
            nextRowkey = jsonArrays.get("nextRowkey").toString();
            if (StringUtils.isEmpty(nextRowkey)) {
                flag = false;
            } else {
                startRowkey = nextRowkey;
            }
        }
        return dakamingxiList3;
    }

    private static Dakamingxi arrayIdToString(JSONObject jsonobejct,Dakamingxi sBuffer,String site) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");//获得当前日期
        LocalDate localDate=LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        sBuffer.setSiteid(site);
        sBuffer.setFirsttime(jsonobejct.getString("time").toString());
        sBuffer.setSwtime(jsonobejct.getString("time").toString());
        sBuffer.setAccount(jsonobejct.getString("stationMac").toString().trim().replace("-", ""));
        sBuffer.setDate(sf.parse(localDate.format(formatter)));
        sBuffer.setUname(jsonobejct.getString("detail"));
        sBuffer.setMac(jsonobejct.getString("stationMac"));
        return sBuffer;

    }
}
